import 'package:amap_flutter_location/amap_flutter_location.dart';
import 'package:amap_flutter_map/amap_flutter_map.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/src/rx_types/rx_types.dart';
import 'package:industry_net/base/common/keys.dart';
import 'package:permission_handler/permission_handler.dart';
import 'location.dart';
import 'package:industry_net/base/common/location/state.dart';
import 'package:industry_net/base/common/util.dart';
import 'package:amap_flutter_base/amap_flutter_base.dart';

class LocationController {
  final LocationState state = LocationState();
  VoidCallback? callback;
  VoidCallback? paintCallback;

  final location = AMapFlutterLocation();
  var md = Location().obs;

  LocationController() {
    location.onLocationChanged().listen((event) {
      Get.log(event.toString());
      md.value = Location.fromJson(event);
      if (callback != null) {
        callback!();
      }
    });
  }

  void register() {
    AMapFlutterLocation.setApiKey(key_amap_android, key_amap_ios);
    AMapFlutterLocation.updatePrivacyAgree(true);
    AMapFlutterLocation.updatePrivacyShow(true, true);
  }

  void startLocation() async {
    var isCanLocation = await requestLocationPermission();
    if (isCanLocation) {
      location.startLocation();
    }
  }

  Future<bool> requestLocationPermission() async {
    //获取当前的权限
    var status = await Permission.storage.status;
    if (status == PermissionStatus.granted) {
      //已经授权
      return true;
    } else {
      //未授权则发起一次申请
      status = await Permission.storage.request();
      if (status == PermissionStatus.granted) {
        return true;
      } else {
        return false;
      }
    }
  }

  Future<AMapWidget> createMap() async {
    var icon = await BitmapDescriptor.fromAssetImage(
        ImageConfiguration(size: Size(20.r, 20.r), devicePixelRatio: 3),
        'avatar_default.png'.imgPathMe,
        mipmaps: false);
    var _selfMarker = Marker(
        position: md.value.position,
        icon: icon,
        infoWindow: InfoWindow(title: md.value.address));
    state.markers[_selfMarker.id] = _selfMarker;
    return AMapWidget(
      apiKey: state.apiKey,
      privacyStatement: state.statement,
      markers: Set<Marker>.of(state.markers.values),
      initialCameraPosition:
          CameraPosition(target: md.value.position, zoom: 16),
      compassEnabled: true,
      scaleEnabled: state.scaleEnable,
      // scrollGesturesEnabled: state.paintState.value != MapPaintState.painting,
      // zoomGesturesEnabled: state.paintState.value != MapPaintState.painting,
      scrollGesturesEnabled: true,
      zoomGesturesEnabled: true,
      mapType: state.mapType,
      polygons: Set<Polygon>.of(state.polygons.values),
      polylines: Set<Polyline>.of(state.poylines.values),
      onTap: (argument) {
        if (state.paintState.value == MapPaintState.painting) {
          state.points.add(argument);
          paint();
        }
      },
      onMapCreated: onMapCreated,
    );
  }

  void backOrigin() {
    state.mapCtrl?.moveCamera(CameraUpdate.newCameraPosition(
        CameraPosition(target: md.value.position, tilt: 0, zoom: 16)));
  }

  void paint() {
    setMarkers(points: state.points);

    if (state.paintState.value == MapPaintState.finish) {
      setPolygon(points: state.points);
      setPolyline(points: []);
    } else {
      setPolyline(points: state.points);
      if (state.paintState.value == MapPaintState.painting) {
        setPolygon(points: []);
      }
    }

    if (paintCallback != null) {
      paintCallback!();
    }
  }

  void onMapCreated(AMapController controller) {
    state.mapCtrl = controller;
  }

  void setPolygon({required List<LatLng> points}) {
    state.polygons = {};
    if (points.isEmpty) {
      return;
    }
    final Polygon polygon = Polygon(
      strokeColor: const Color(0xffe69138),
      fillColor: const Color(0xcce69138),
      strokeWidth: 3.r,
      points: points,
    );
    state.polygons[polygon.id] = polygon;
  }

  void setPolyline({required List<LatLng> points}) {
    state.poylines = {};
    if (points.isEmpty) {
      return;
    }
    final Polyline polyline = Polyline(
      color: const Color(0xffe69138),
      width: 3.r,
      points: points,
    );
    state.poylines[polyline.id] = polyline;
  }

  Marker _createMarker(LatLng point, int index) {
    return Marker(
      position: point,
      infoWindowEnable: false,
      draggable: true,
      onDragEnd: (id, endPosition) {
        state.points.removeAt(index);
        state.points.insert(index, endPosition);
        paint();
      },
      onTap: (argument) {
        if (index == 0) {
          state.paintState.value = MapPaintState.finish;
          paint();
        }
      },
    );
  }

  void setMarkers({required List<LatLng> points}) {
    state.markers = {};
    if (points.isEmpty) {
      return;
    }
    for (var i = 0; i < points.length; i++) {
      var e = points[i];
      var marker = _createMarker(e, i);
      state.markers[marker.id] = marker;
    }
  }

  dispose() {
    location.stopLocation();
    location.destroy();
  }
}
